package com.jiwanqing.demo.mapper.impl;

import com.jiwanqing.demo.entity.Student;
import com.jiwanqing.demo.mapper.IStudentMapper;
import com.jiwanqing.demo.util.JDBCUtil;

import java.sql.*;
import java.util.ArrayList;
import java.util.List;

public class StudentMapperImpl implements IStudentMapper {


    @Override
    public Student save(Student student) {
        System.out.println("mapper:教务数据保存完毕");
        System.out.println("mapper:数据抄送返回到service");
        return student;
    }

    @Override
    public List<Student> selectAll() {
        String sql = "SELECT * FROM student";
        Connection connection = null;
        PreparedStatement statement = null;
        ResultSet resultset = null;
        List<Student> students = new ArrayList<>();
        try {
            connection = JDBCUtil.getCon();
            statement = connection.prepareStatement(sql);
            resultset = statement.executeQuery();
            while (resultset.next()) {
                Student s = new Student();
                s.setId(resultset.getInt("id"));
                s.setUsername(resultset.getString("username"));
                s.setFraction(resultset.getInt("fraction"));
                s.setGrade(resultset.getString("grade"));
                students.add(s);
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);

        } finally {
            JDBCUtil.closeAll(resultset, statement, connection);
        }
        return students;
    }

    @Override
    public int insert(Student student) {
        String sql = "INSERT INTO student(username,fraction)VALUES (?,?);";
        Connection connection = null;
        PreparedStatement statement = null;
        int row = 0;

        try {
            connection = JDBCUtil.getCon();
            statement = connection.prepareStatement(sql);
            statement.setString(1,student.getUsername());
            statement.setInt(2,student.getFraction());
            row= statement.executeUpdate();
        }catch (SQLException e){
            throw new RuntimeException(e);

        }finally {
            JDBCUtil.closeAll(null,statement,connection);
        }
        return row;
    }











}

